import 'package:flutter_account_book/utils/db/db_helper.dart';
import 'package:flutter_account_book/utils/db/entities/record_type.dart';

class RecordTypeDao extends DbDao<RecordType> {
  RecordTypeDao({required super.db});
  @override
  String get tableName => "record_types";

  Future<List<RecordType>> flowAll(int isIncome) async {
    List list = await db.rawQuery(
        'SELECT * FROM $tableName WHERE isIncome = ? ORDER BY `order`',
        [isIncome]);
    return list.map((item) => RecordType.fromJson(item)).toList();
  }

  Future<RecordType?> getById(int id) async {
    var result =
        await db.rawQuery('select * from $tableName where id = ?', [id]);
    if (result.isNotEmpty) {
      return RecordType.fromJson(result[0]);
    }
    return null;
  }

  Future<bool> has(int id) async {
    RecordType? recordType = await getById(id);
    return recordType != null;
  }

  Future<int> update(RecordType recordType) async {
    return await db.update(tableName, recordType.toJson(),
        where: 'id = ?', whereArgs: [recordType.id]);
  }

  Future<int> delete(RecordType recordType) async {
    return await db
        .delete(tableName, where: 'id = ?', whereArgs: [recordType.id]);
  }

  Future<int> maxOrder() async {
    List result = await db
        .rawQuery('SELECT MAX(`order`) max FROM $tableName where id >= 0');
    if (result.isNotEmpty) {
      return result[0]['max'] as int? ?? 0;
    }
    return 0;
  }

  Future<int> idsSum() async {
    List result =
        await db.rawQuery('SELECT SUM(id) sum FROM $tableName where id >= 0');
    if (result.isNotEmpty) {
      return result[0]['sum'] as int? ?? 0;
    }
    return 0;
  }

  Future<int> getUnusedId() async {
    var id = 1;
    var idsS = await idsSum();
    while (id & idsS != 0) {
      id = id << 1;
    }
    return id;
  }
}
